//
//  HMOAuthViewController.swift
//  Weibo
//
//  Created by fuyu on 2017/7/24.
//  Copyright © 2017年 itteacher. All rights reserved.
//

import UIKit
import SVProgressHUD

//OAuth登陆界面

let AppKey = "2379901287"

let AppSecret = "debadaabc2fff65bb121b81de7f9b25f"

//授权回调地址
let Redirect_uri = "http://www.itcast.cn"


class HMOAuthViewController: UIViewController {
    //懒加载控件
    private lazy var webView: UIWebView = UIWebView()
    
    //  重写loadView,自定义控制器的视图
    override func loadView() {
        webView.delegate = self
        view = webView
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white
        setupNavUI()
        loadLogin()
    }
    
    //  设置导航栏按钮
    private func setupNavUI() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: #selector(cancelAction))
        navigationItem.title = "微博登陆"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFillAction))
    }
    
    //加载第三方登陆
    func loadLogin() {
        
        //请求地址
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(AppKey)&redirect_uri=\(Redirect_uri)"
        //创建url对象
        let url = URL(string: urlStr)
        //加载web页面
        webView.loadRequest(URLRequest(url:url!))

    }
    //  MARK: --导航栏按钮点击事件处理
   @objc private func cancelAction() {
        
        self.dismiss(animated: true, completion: nil)
    }
    
   @objc private func autoFillAction() {
        
    webView.stringByEvaluatingJavaScript(from: "document.getElementById('userId').value = '15538552471';document.getElementById('passwd').value = 'pmy8910810';document.getElementById('passwd').focus();")
    }
}


//MARK: -- UIWebViewDelegate
extension HMOAuthViewController:
UIWebViewDelegate {
    
    //将要加载网络请求
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest,navigationType: UIWebViewNavigationType) ->Bool {
        if request.url?.absoluteString.hasPrefix(Redirect_uri) == true {
            //代码到此,表示以授权回收地址开头
            //query: url后面的参数
            if let query = request.url?.query, query.hasPrefix("code=") {
                
                //表示是我们需要的参数
                //截取授权码字符串
                let code = query.substring(from: "code=".endIndex)
                //通过code授权码获取
//                requestAccessToken(code: code)
                HMUserAccountViewModel.sharedViewModel.requestAccessToken(code: code, callBack: { (isSuccess: Bool) in
                    if isSuccess {
                        //  登录成功
                        print("登录成功")
                        //  注意点： 需要让当前OAuthVCdismis完成以后再去切换根视图控制器，否则MainVC没有释放
                        self.dismiss(animated: false, completion: {
                            //  进入欢迎页面
                            //  切换根视图控制器
                            NotificationCenter.default.post(name: NSNotification.Name(SwitchRootVCNotificationName), object: self)
                        })
                        

                    } else {
                        //  登录失败
                        print("登录失败")
                    }
                })

                
            } else {
                
                //取消授权
                self.dismiss(animated: true, completion: nil)
            }
            //如果是false会执行加载失败的方法
            return false
            
        }
        //  true: 运行加载这次请求地址，false: 不允许加载这次请求地址
        return true
    }
    
    //已经开始加载请求
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    //加载完成
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    //加载失败
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        //  如果是false会执行加载失败的方法
        SVProgressHUD.dismiss()
    }
}
